package com.tzinfo.tzt.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tzinfo.data.TztData;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.Car4SModeActivity;
import com.tzinfo.tzt.activity.util.FragmentHomeListviewAdapter;
import com.tzinfo.tzt.util.HttpUtils;
import com.tzinfo.tzt.util.ResultMessage;
import com.tzinfo.tzt.util.Resultmap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2014/11/12.
 */
public class MyFragment0 extends Fragment {
    private PullToRefreshListView listView;
    private Context context;
    private TextView editText1;
    private Spinner spinner;
    int pagesize = 5;
    private boolean isLoadingData = false;
    int page;
    List<Resultmap> listData;
    private FragmentHomeListviewAdapter fragmentHomeListviewAdapter;
    private static final String[] areaids = {"椒江", "黄岩", "路桥", "临海" ,
            "温岭", "玉环", "仙居", "三门", "天台","外地"};
    private int areais = 1;
    private ArrayAdapter<String> arrayAdapter = null;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = activity;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page = 1;
        //这里我只是简单的用num区别标签，其实具体应用中可以使用真实的fragment对象来作为叶片
    }

    /**
     * 为Fragment加载布局时调用*
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.myfragment0_pager_list, null);
        spinner = (Spinner) view.findViewById(R.id.myFragment0_carplateserachbar_spinner);
        arrayAdapter = new ArrayAdapter(context,android.R.layout.simple_spinner_item,areaids);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item );
        spinner.setAdapter(arrayAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                areais=position + 1;
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });


        editText1 = (EditText) view.findViewById(R.id.myFragment0_carplateserachbar_et);
        listView = (PullToRefreshListView) view.findViewById(R.id.myFragment0_home_pager_listView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position > 0) {
                    long _id = ((HeaderViewListAdapter) parent.getAdapter()).getItemId(position);
                    Intent intent = new Intent(context, Car4SModeActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("Id", String.valueOf(_id));
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }
            }
        });
        if (listData != null) {
            fragmentHomeListviewAdapter = new FragmentHomeListviewAdapter(context, listData);
            listView.setAdapter(fragmentHomeListviewAdapter);
        }

        editText1.addTextChangedListener(textWatcher);
        listView.setMode(PullToRefreshBase.Mode.BOTH);

        ILoadingLayout endLabels = listView.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("上拉加载更多");
        endLabels.setReleaseLabel("松开加载");
        endLabels.setRefreshingLabel("正在加载");


        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(
                        context,
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);


                if (!isLoadingData) {
                    page = 1;
                    refreshView.getLoadingLayoutProxy()
                            .setLastUpdatedLabel(label);
                    new GetDataTask().execute();
                }

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(
                        context,
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                // 显示最后更新的时间
                if (!isLoadingData) {
                    refreshView.getLoadingLayoutProxy()
                            .setLastUpdatedLabel(label);
                    new GetDataTask().execute();
                }
            }
        });

        editText1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                SearchTask aa = new SearchTask();
                aa.execute();
                return true;
            }
        });

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        page--;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new GetDataTask().execute();
    }

    public class SearchTask extends AsyncTask<String, Void, ResultMessage> {

        @Override
        protected ResultMessage doInBackground(String... params) {
            ResultMessage result;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("areaid", String.valueOf(areais)));
            //   pairs.add(new BasicNameValuePair("Title", ""));
            pairs.add(new BasicNameValuePair("page", "1"));
            pairs.add(new BasicNameValuePair("pagesize", "6"));
            pairs.add(new BasicNameValuePair("Title", editText1.getText().toString()));
            String GetDataUrl = "http://auto.tzinfo.net/mob/api/Car4SList.ashx";
            String loginResultString = HttpUtils.doPostMethod(GetDataUrl, pairs);

            Gson gson = new Gson();
            result = gson.fromJson(loginResultString, ResultMessage.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage result) {
            super.onPostExecute(result);
            if (result.getSuccess() == true) {
                listView.setAdapter(new FragmentHomeListviewAdapter(context, result.getData()));
            } else {
                Toast.makeText(context, result.getErrorMsg(), Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    public class GetDataTask extends AsyncTask<String, Void, ResultMessage> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (isLoadingData) {
                this.cancel(true);
                return;
            }
            isLoadingData = true;

        }

        @Override
        protected ResultMessage doInBackground(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            ResultMessage result = null;
            pairs.add(new BasicNameValuePair("areaid", String.valueOf(areais)));
            //   pairs.add(new BasicNameValuePair("Title", ""));
            pairs.add(new BasicNameValuePair("page", String.valueOf(page)));
            pairs.add(new BasicNameValuePair("pagesize", String.valueOf(pagesize)));
            String GetDataUrl = "http://auto.tzinfo.net/mob/api/Car4SList.ashx";
            String car4sDataString = HttpUtils.doPostMethod(GetDataUrl, pairs);
            Gson gson = new Gson();
            result = gson.fromJson(car4sDataString, ResultMessage.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage result) {
            super.onPostExecute(result);
            if (result.getSuccess() == true) {
                if (fragmentHomeListviewAdapter == null || page == 1) {
                    listData = result.getData();
                } else {
                    listData.addAll(result.getData());
                }
                if (listData.size() == pagesize) {
                    fragmentHomeListviewAdapter = new FragmentHomeListviewAdapter(context, listData);
                    listView.setAdapter(fragmentHomeListviewAdapter);
                }
                page++;
                fragmentHomeListviewAdapter.notifyDataSetChanged();
                listView.onRefreshComplete();
                isLoadingData = false;
            } else {
                Toast.makeText(context, result.getErrorMsg(), Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {
                //        new SearchTask().execute();
                listView.setAdapter(fragmentHomeListviewAdapter);
            }

        }
    };


}
